package com.leyou.sms.mq;

import com.leyou.common.constants.MQConstants;
import com.leyou.common.utils.RegexUtils;
import com.leyou.sms.utils.SmsUtils;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.Map;

import static com.leyou.common.constants.MQConstants.ExchangeConstants.SMS_EXCHANGE_NAME;
import static com.leyou.common.constants.MQConstants.QueueConstants.SMS_VERIFY_CODE_QUEUE;

@Component
public class MessageListener {

    @Autowired
    private SmsUtils smsUtils;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = SMS_VERIFY_CODE_QUEUE, durable = "true"),
            exchange = @Exchange(name ="jhj", type = ExchangeTypes.TOPIC),
            key = SMS_EXCHANGE_NAME
    ))
    public void listenVerifyCodeMessage(Map<String, String> msg){
        if(CollectionUtils.isEmpty(msg)){
            return;
        }

        String phone = msg.get("phone");
        if(!RegexUtils.isPhone(phone)){
            return;
        }

        String code = msg.get("code");
        if(!RegexUtils.isCodeValid(code)){
            return;
        }

        try {
            smsUtils.sendVerifyCode(phone, code);
        } catch (Exception e) {
            System.out.println("短信发送异常");
            e.printStackTrace();
        }

    }
}
